{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f3ea935f-3f89-4e01-be8d-c0b7d499f002",
   "metadata": {},
   "source": [
    "# KNN"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bf6eba12-54e7-4a71-bb8f-38d92a49e18c",
   "metadata": {},
   "source": [
    "### 一种分类和回归算法\n",
    "- k个最近邻居，k-nearest-neighbours\n",
    "- 通过分析样本与邻居的相似度对样本进行判断分类\n",
    "- 一般通过与训练样本之间“距离”的计算判断\n",
    "- 通过训练数据集建立起的分类器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 124,
   "id": "ac01b640-c595-4c33-aebd-61a8343e9a9b",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "knn=KNeighborsClassifier(n_neighbors=5, weights=\"uniform\", algorithm=\"auto\", leaf_size=30, p=2, metric=\"minkowski\", metric_params=None, n_jobs=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebd1fa37-f039-403c-868b-f2c657265d49",
   "metadata": {},
   "source": [
    "- n_neighbors  ---k近邻的k值，默认值是5\n",
    "- weights  ---预测时邻居的权重， uniform表示邻居权重一样大，distance表示距离小的权重大\n",
    "- metric ---距离计算公式， ‘minkowski’闵氏距离\n",
    "- p ---闵氏距离的参数，p=2就是欧式距离，p=1就是曼哈顿距离\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 125,
   "id": "b30e7411-23c2-432c-96d3-12d6671e5b26",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn import datasets\n",
    "# 导入sklearn自带的iris数据集                                #step1\n",
    "iris = datasets.load_iris()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bb2baae1-baf3-408c-a742-b863707eeea2",
   "metadata": {},
   "source": [
    "在机器学习和统计学领域，Iris数据集是一个非常著名的数据集，由R.A. Fisher在1936年整理\n",
    "。这个数据集包含了150个样本，分为3种不同类型的鸢尾花（Setosa、Versicolour和Virginica），每种类型50个样本，每个样本包含4个特征：花萼长度、花萼宽度、花瓣长度和花瓣宽度。这个数据集常用于分类算法的测试和教学。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 126,
   "id": "6cecbad7-250a-46b6-900e-68d62b3ecad8",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'data': array([[5.1, 3.5, 1.4, 0.2],\n",
       "        [4.9, 3. , 1.4, 0.2],\n",
       "        [4.7, 3.2, 1.3, 0.2],\n",
       "        [4.6, 3.1, 1.5, 0.2],\n",
       "        [5. , 3.6, 1.4, 0.2],\n",
       "        [5.4, 3.9, 1.7, 0.4],\n",
       "        [4.6, 3.4, 1.4, 0.3],\n",
       "        [5. , 3.4, 1.5, 0.2],\n",
       "        [4.4, 2.9, 1.4, 0.2],\n",
       "        [4.9, 3.1, 1.5, 0.1],\n",
       "        [5.4, 3.7, 1.5, 0.2],\n",
       "        [4.8, 3.4, 1.6, 0.2],\n",
       "        [4.8, 3. , 1.4, 0.1],\n",
       "        [4.3, 3. , 1.1, 0.1],\n",
       "        [5.8, 4. , 1.2, 0.2],\n",
       "        [5.7, 4.4, 1.5, 0.4],\n",
       "        [5.4, 3.9, 1.3, 0.4],\n",
       "        [5.1, 3.5, 1.4, 0.3],\n",
       "        [5.7, 3.8, 1.7, 0.3],\n",
       "        [5.1, 3.8, 1.5, 0.3],\n",
       "        [5.4, 3.4, 1.7, 0.2],\n",
       "        [5.1, 3.7, 1.5, 0.4],\n",
       "        [4.6, 3.6, 1. , 0.2],\n",
       "        [5.1, 3.3, 1.7, 0.5],\n",
       "        [4.8, 3.4, 1.9, 0.2],\n",
       "        [5. , 3. , 1.6, 0.2],\n",
       "        [5. , 3.4, 1.6, 0.4],\n",
       "        [5.2, 3.5, 1.5, 0.2],\n",
       "        [5.2, 3.4, 1.4, 0.2],\n",
       "        [4.7, 3.2, 1.6, 0.2],\n",
       "        [4.8, 3.1, 1.6, 0.2],\n",
       "        [5.4, 3.4, 1.5, 0.4],\n",
       "        [5.2, 4.1, 1.5, 0.1],\n",
       "        [5.5, 4.2, 1.4, 0.2],\n",
       "        [4.9, 3.1, 1.5, 0.2],\n",
       "        [5. , 3.2, 1.2, 0.2],\n",
       "        [5.5, 3.5, 1.3, 0.2],\n",
       "        [4.9, 3.6, 1.4, 0.1],\n",
       "        [4.4, 3. , 1.3, 0.2],\n",
       "        [5.1, 3.4, 1.5, 0.2],\n",
       "        [5. , 3.5, 1.3, 0.3],\n",
       "        [4.5, 2.3, 1.3, 0.3],\n",
       "        [4.4, 3.2, 1.3, 0.2],\n",
       "        [5. , 3.5, 1.6, 0.6],\n",
       "        [5.1, 3.8, 1.9, 0.4],\n",
       "        [4.8, 3. , 1.4, 0.3],\n",
       "        [5.1, 3.8, 1.6, 0.2],\n",
       "        [4.6, 3.2, 1.4, 0.2],\n",
       "        [5.3, 3.7, 1.5, 0.2],\n",
       "        [5. , 3.3, 1.4, 0.2],\n",
       "        [7. , 3.2, 4.7, 1.4],\n",
       "        [6.4, 3.2, 4.5, 1.5],\n",
       "        [6.9, 3.1, 4.9, 1.5],\n",
       "        [5.5, 2.3, 4. , 1.3],\n",
       "        [6.5, 2.8, 4.6, 1.5],\n",
       "        [5.7, 2.8, 4.5, 1.3],\n",
       "        [6.3, 3.3, 4.7, 1.6],\n",
       "        [4.9, 2.4, 3.3, 1. ],\n",
       "        [6.6, 2.9, 4.6, 1.3],\n",
       "        [5.2, 2.7, 3.9, 1.4],\n",
       "        [5. , 2. , 3.5, 1. ],\n",
       "        [5.9, 3. , 4.2, 1.5],\n",
       "        [6. , 2.2, 4. , 1. ],\n",
       "        [6.1, 2.9, 4.7, 1.4],\n",
       "        [5.6, 2.9, 3.6, 1.3],\n",
       "        [6.7, 3.1, 4.4, 1.4],\n",
       "        [5.6, 3. , 4.5, 1.5],\n",
       "        [5.8, 2.7, 4.1, 1. ],\n",
       "        [6.2, 2.2, 4.5, 1.5],\n",
       "        [5.6, 2.5, 3.9, 1.1],\n",
       "        [5.9, 3.2, 4.8, 1.8],\n",
       "        [6.1, 2.8, 4. , 1.3],\n",
       "        [6.3, 2.5, 4.9, 1.5],\n",
       "        [6.1, 2.8, 4.7, 1.2],\n",
       "        [6.4, 2.9, 4.3, 1.3],\n",
       "        [6.6, 3. , 4.4, 1.4],\n",
       "        [6.8, 2.8, 4.8, 1.4],\n",
       "        [6.7, 3. , 5. , 1.7],\n",
       "        [6. , 2.9, 4.5, 1.5],\n",
       "        [5.7, 2.6, 3.5, 1. ],\n",
       "        [5.5, 2.4, 3.8, 1.1],\n",
       "        [5.5, 2.4, 3.7, 1. ],\n",
       "        [5.8, 2.7, 3.9, 1.2],\n",
       "        [6. , 2.7, 5.1, 1.6],\n",
       "        [5.4, 3. , 4.5, 1.5],\n",
       "        [6. , 3.4, 4.5, 1.6],\n",
       "        [6.7, 3.1, 4.7, 1.5],\n",
       "        [6.3, 2.3, 4.4, 1.3],\n",
       "        [5.6, 3. , 4.1, 1.3],\n",
       "        [5.5, 2.5, 4. , 1.3],\n",
       "        [5.5, 2.6, 4.4, 1.2],\n",
       "        [6.1, 3. , 4.6, 1.4],\n",
       "        [5.8, 2.6, 4. , 1.2],\n",
       "        [5. , 2.3, 3.3, 1. ],\n",
       "        [5.6, 2.7, 4.2, 1.3],\n",
       "        [5.7, 3. , 4.2, 1.2],\n",
       "        [5.7, 2.9, 4.2, 1.3],\n",
       "        [6.2, 2.9, 4.3, 1.3],\n",
       "        [5.1, 2.5, 3. , 1.1],\n",
       "        [5.7, 2.8, 4.1, 1.3],\n",
       "        [6.3, 3.3, 6. , 2.5],\n",
       "        [5.8, 2.7, 5.1, 1.9],\n",
       "        [7.1, 3. , 5.9, 2.1],\n",
       "        [6.3, 2.9, 5.6, 1.8],\n",
       "        [6.5, 3. , 5.8, 2.2],\n",
       "        [7.6, 3. , 6.6, 2.1],\n",
       "        [4.9, 2.5, 4.5, 1.7],\n",
       "        [7.3, 2.9, 6.3, 1.8],\n",
       "        [6.7, 2.5, 5.8, 1.8],\n",
       "        [7.2, 3.6, 6.1, 2.5],\n",
       "        [6.5, 3.2, 5.1, 2. ],\n",
       "        [6.4, 2.7, 5.3, 1.9],\n",
       "        [6.8, 3. , 5.5, 2.1],\n",
       "        [5.7, 2.5, 5. , 2. ],\n",
       "        [5.8, 2.8, 5.1, 2.4],\n",
       "        [6.4, 3.2, 5.3, 2.3],\n",
       "        [6.5, 3. , 5.5, 1.8],\n",
       "        [7.7, 3.8, 6.7, 2.2],\n",
       "        [7.7, 2.6, 6.9, 2.3],\n",
       "        [6. , 2.2, 5. , 1.5],\n",
       "        [6.9, 3.2, 5.7, 2.3],\n",
       "        [5.6, 2.8, 4.9, 2. ],\n",
       "        [7.7, 2.8, 6.7, 2. ],\n",
       "        [6.3, 2.7, 4.9, 1.8],\n",
       "        [6.7, 3.3, 5.7, 2.1],\n",
       "        [7.2, 3.2, 6. , 1.8],\n",
       "        [6.2, 2.8, 4.8, 1.8],\n",
       "        [6.1, 3. , 4.9, 1.8],\n",
       "        [6.4, 2.8, 5.6, 2.1],\n",
       "        [7.2, 3. , 5.8, 1.6],\n",
       "        [7.4, 2.8, 6.1, 1.9],\n",
       "        [7.9, 3.8, 6.4, 2. ],\n",
       "        [6.4, 2.8, 5.6, 2.2],\n",
       "        [6.3, 2.8, 5.1, 1.5],\n",
       "        [6.1, 2.6, 5.6, 1.4],\n",
       "        [7.7, 3. , 6.1, 2.3],\n",
       "        [6.3, 3.4, 5.6, 2.4],\n",
       "        [6.4, 3.1, 5.5, 1.8],\n",
       "        [6. , 3. , 4.8, 1.8],\n",
       "        [6.9, 3.1, 5.4, 2.1],\n",
       "        [6.7, 3.1, 5.6, 2.4],\n",
       "        [6.9, 3.1, 5.1, 2.3],\n",
       "        [5.8, 2.7, 5.1, 1.9],\n",
       "        [6.8, 3.2, 5.9, 2.3],\n",
       "        [6.7, 3.3, 5.7, 2.5],\n",
       "        [6.7, 3. , 5.2, 2.3],\n",
       "        [6.3, 2.5, 5. , 1.9],\n",
       "        [6.5, 3. , 5.2, 2. ],\n",
       "        [6.2, 3.4, 5.4, 2.3],\n",
       "        [5.9, 3. , 5.1, 1.8]]),\n",
       " 'target': array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "        0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n",
       "        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,\n",
       "        2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]),\n",
       " 'frame': None,\n",
       " 'target_names': array(['setosa', 'versicolor', 'virginica'], dtype='<U10'),\n",
       " 'DESCR': '.. _iris_dataset:\\n\\nIris plants dataset\\n--------------------\\n\\n**Data Set Characteristics:**\\n\\n:Number of Instances: 150 (50 in each of three classes)\\n:Number of Attributes: 4 numeric, predictive attributes and the class\\n:Attribute Information:\\n    - sepal length in cm\\n    - sepal width in cm\\n    - petal length in cm\\n    - petal width in cm\\n    - class:\\n            - Iris-Setosa\\n            - Iris-Versicolour\\n            - Iris-Virginica\\n\\n:Summary Statistics:\\n\\n============== ==== ==== ======= ===== ====================\\n                Min  Max   Mean    SD   Class Correlation\\n============== ==== ==== ======= ===== ====================\\nsepal length:   4.3  7.9   5.84   0.83    0.7826\\nsepal width:    2.0  4.4   3.05   0.43   -0.4194\\npetal length:   1.0  6.9   3.76   1.76    0.9490  (high!)\\npetal width:    0.1  2.5   1.20   0.76    0.9565  (high!)\\n============== ==== ==== ======= ===== ====================\\n\\n:Missing Attribute Values: None\\n:Class Distribution: 33.3% for each of 3 classes.\\n:Creator: R.A. Fisher\\n:Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)\\n:Date: July, 1988\\n\\nThe famous Iris database, first used by Sir R.A. Fisher. The dataset is taken\\nfrom Fisher\\'s paper. Note that it\\'s the same as in R, but not as in the UCI\\nMachine Learning Repository, which has two wrong data points.\\n\\nThis is perhaps the best known database to be found in the\\npattern recognition literature.  Fisher\\'s paper is a classic in the field and\\nis referenced frequently to this day.  (See Duda & Hart, for example.)  The\\ndata set contains 3 classes of 50 instances each, where each class refers to a\\ntype of iris plant.  One class is linearly separable from the other 2; the\\nlatter are NOT linearly separable from each other.\\n\\n|details-start|\\n**References**\\n|details-split|\\n\\n- Fisher, R.A. \"The use of multiple measurements in taxonomic problems\"\\n  Annual Eugenics, 7, Part II, 179-188 (1936); also in \"Contributions to\\n  Mathematical Statistics\" (John Wiley, NY, 1950).\\n- Duda, R.O., & Hart, P.E. (1973) Pattern Classification and Scene Analysis.\\n  (Q327.D83) John Wiley & Sons.  ISBN 0-471-22361-1.  See page 218.\\n- Dasarathy, B.V. (1980) \"Nosing Around the Neighborhood: A New System\\n  Structure and Classification Rule for Recognition in Partially Exposed\\n  Environments\".  IEEE Transactions on Pattern Analysis and Machine\\n  Intelligence, Vol. PAMI-2, No. 1, 67-71.\\n- Gates, G.W. (1972) \"The Reduced Nearest Neighbor Rule\".  IEEE Transactions\\n  on Information Theory, May 1972, 431-433.\\n- See also: 1988 MLC Proceedings, 54-64.  Cheeseman et al\"s AUTOCLASS II\\n  conceptual clustering system finds 3 classes in the data.\\n- Many, many more ...\\n\\n|details-end|\\n',\n",
       " 'feature_names': ['sepal length (cm)',\n",
       "  'sepal width (cm)',\n",
       "  'petal length (cm)',\n",
       "  'petal width (cm)'],\n",
       " 'filename': 'iris.csv',\n",
       " 'data_module': 'sklearn.datasets.data'}"
      ]
     },
     "execution_count": 126,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "iris"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 127,
   "id": "02b20aa6-a7ea-4935-9223-d56c38de89d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.model_selection import train_test_split        ##重点记忆\n",
    "X_train,X_test,y_train,y_test=train_test_split(iris.data,iris.target,test_size=0.3,random_state=1024)  \n",
    "                                                                                ##random_state 随机状态\n",
    "##Step2:拆分成训练集和测试集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 128,
   "id": "22082418-ca40-482e-b9d7-30fc878eb42c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-6 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: black;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-6 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-6 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-6 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-6 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-6 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-6 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-6 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-6 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-6 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-6 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-6 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-6 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-6 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-6 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-6 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 1ex;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-6 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-6 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-6 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-6\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>KNeighborsClassifier(n_jobs=1)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-6\" type=\"checkbox\" checked><label for=\"sk-estimator-id-6\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;&nbsp;KNeighborsClassifier<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.4/modules/generated/sklearn.neighbors.KNeighborsClassifier.html\">?<span>Documentation for KNeighborsClassifier</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>KNeighborsClassifier(n_jobs=1)</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "KNeighborsClassifier(n_jobs=1)"
      ]
     },
     "execution_count": 128,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 实例化模型并训练\n",
    "#调用 KNeighborsClassifier()\n",
    "knn.fit(X_train,y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dcc29cae-0bed-4fe2-847c-f6f255a5055a",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 129,
   "id": "ada055b7-a395-4ed9-a954-3f138264b0e6",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[6.2, 2.8, 4.8, 1.8],\n",
       "       [7.9, 3.8, 6.4, 2. ],\n",
       "       [4.7, 3.2, 1.3, 0.2],\n",
       "       [5. , 2. , 3.5, 1. ],\n",
       "       [6.5, 3. , 5.2, 2. ],\n",
       "       [7.1, 3. , 5.9, 2.1],\n",
       "       [7.3, 2.9, 6.3, 1.8],\n",
       "       [5.1, 3.8, 1.9, 0.4],\n",
       "       [4.4, 3.2, 1.3, 0.2],\n",
       "       [6.2, 2.2, 4.5, 1.5],\n",
       "       [6.9, 3.1, 5.1, 2.3],\n",
       "       [7.2, 3.2, 6. , 1.8],\n",
       "       [5.6, 2.9, 3.6, 1.3],\n",
       "       [7.7, 3.8, 6.7, 2.2],\n",
       "       [6.3, 3.3, 4.7, 1.6],\n",
       "       [7.4, 2.8, 6.1, 1.9],\n",
       "       [6.8, 3.2, 5.9, 2.3],\n",
       "       [6.4, 3.2, 4.5, 1.5],\n",
       "       [6. , 2.9, 4.5, 1.5],\n",
       "       [6.4, 3.1, 5.5, 1.8],\n",
       "       [4.4, 2.9, 1.4, 0.2],\n",
       "       [4.6, 3.6, 1. , 0.2],\n",
       "       [6.4, 2.8, 5.6, 2.1],\n",
       "       [5.4, 3.4, 1.5, 0.4],\n",
       "       [5.7, 2.8, 4.5, 1.3],\n",
       "       [4.9, 3.1, 1.5, 0.2],\n",
       "       [5.7, 2.6, 3.5, 1. ],\n",
       "       [5. , 3.3, 1.4, 0.2],\n",
       "       [6. , 2.2, 4. , 1. ],\n",
       "       [6. , 3.4, 4.5, 1.6],\n",
       "       [5.7, 2.8, 4.1, 1.3],\n",
       "       [5.4, 3.7, 1.5, 0.2],\n",
       "       [6.1, 2.8, 4.7, 1.2],\n",
       "       [4.8, 3. , 1.4, 0.3],\n",
       "       [5.8, 2.7, 3.9, 1.2],\n",
       "       [5. , 3.2, 1.2, 0.2],\n",
       "       [6.3, 3.3, 6. , 2.5],\n",
       "       [6.3, 2.8, 5.1, 1.5],\n",
       "       [6. , 2.2, 5. , 1.5],\n",
       "       [6.5, 3.2, 5.1, 2. ],\n",
       "       [5.7, 3. , 4.2, 1.2],\n",
       "       [5.2, 3.4, 1.4, 0.2],\n",
       "       [5.6, 3. , 4.1, 1.3],\n",
       "       [5.1, 3.8, 1.6, 0.2],\n",
       "       [7.7, 2.8, 6.7, 2. ],\n",
       "       [7.2, 3.6, 6.1, 2.5],\n",
       "       [5.5, 3.5, 1.3, 0.2],\n",
       "       [6.9, 3.2, 5.7, 2.3],\n",
       "       [6.3, 2.5, 5. , 1.9],\n",
       "       [6.4, 3.2, 5.3, 2.3],\n",
       "       [5.5, 2.4, 3.8, 1.1],\n",
       "       [4.9, 2.5, 4.5, 1.7],\n",
       "       [6.1, 2.9, 4.7, 1.4],\n",
       "       [4.4, 3. , 1.3, 0.2],\n",
       "       [7.2, 3. , 5.8, 1.6],\n",
       "       [5.1, 3.7, 1.5, 0.4],\n",
       "       [4.6, 3.1, 1.5, 0.2],\n",
       "       [6.5, 3. , 5.5, 1.8],\n",
       "       [6.1, 3. , 4.6, 1.4],\n",
       "       [6.9, 3.1, 5.4, 2.1],\n",
       "       [5.5, 2.4, 3.7, 1. ],\n",
       "       [5.4, 3.9, 1.3, 0.4],\n",
       "       [4.8, 3. , 1.4, 0.1],\n",
       "       [5.6, 2.7, 4.2, 1.3],\n",
       "       [5.1, 3.4, 1.5, 0.2],\n",
       "       [6.4, 2.8, 5.6, 2.2],\n",
       "       [5.5, 2.6, 4.4, 1.2],\n",
       "       [5. , 3.4, 1.6, 0.4],\n",
       "       [5. , 3.5, 1.3, 0.3],\n",
       "       [6. , 3. , 4.8, 1.8],\n",
       "       [5.7, 4.4, 1.5, 0.4],\n",
       "       [6.8, 3. , 5.5, 2.1],\n",
       "       [5.9, 3. , 5.1, 1.8],\n",
       "       [6.9, 3.1, 4.9, 1.5],\n",
       "       [5.4, 3.4, 1.7, 0.2],\n",
       "       [5.9, 3.2, 4.8, 1.8],\n",
       "       [6.3, 3.4, 5.6, 2.4],\n",
       "       [5.4, 3.9, 1.7, 0.4],\n",
       "       [6.8, 2.8, 4.8, 1.4],\n",
       "       [4.6, 3.2, 1.4, 0.2],\n",
       "       [6.5, 2.8, 4.6, 1.5],\n",
       "       [5.9, 3. , 4.2, 1.5],\n",
       "       [7.7, 2.6, 6.9, 2.3],\n",
       "       [4.8, 3.1, 1.6, 0.2],\n",
       "       [4.3, 3. , 1.1, 0.1],\n",
       "       [5.3, 3.7, 1.5, 0.2],\n",
       "       [5.1, 3.8, 1.5, 0.3],\n",
       "       [5.2, 3.5, 1.5, 0.2],\n",
       "       [7.7, 3. , 6.1, 2.3],\n",
       "       [4.9, 3.6, 1.4, 0.1],\n",
       "       [5.6, 2.5, 3.9, 1.1],\n",
       "       [5.2, 2.7, 3.9, 1.4],\n",
       "       [5.7, 3.8, 1.7, 0.3],\n",
       "       [6.7, 3.1, 4.4, 1.4],\n",
       "       [4.9, 3.1, 1.5, 0.1],\n",
       "       [5.1, 3.3, 1.7, 0.5],\n",
       "       [5.7, 2.9, 4.2, 1.3],\n",
       "       [5.8, 2.7, 4.1, 1. ],\n",
       "       [5.2, 4.1, 1.5, 0.1],\n",
       "       [6.7, 3. , 5. , 1.7],\n",
       "       [6.2, 3.4, 5.4, 2.3],\n",
       "       [5.5, 2.5, 4. , 1.3],\n",
       "       [5.8, 2.7, 5.1, 1.9],\n",
       "       [6.2, 2.9, 4.3, 1.3],\n",
       "       [6.7, 3. , 5.2, 2.3]])"
      ]
     },
     "execution_count": 129,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X_train"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 130,
   "id": "43bd9acd-dfe1-4e65-ae5c-6251c0e0cf78",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.9555555555555556\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       1.00      1.00      1.00        14\n",
      "           1       1.00      0.88      0.93        16\n",
      "           2       0.88      1.00      0.94        15\n",
      "\n",
      "    accuracy                           0.96        45\n",
      "   macro avg       0.96      0.96      0.96        45\n",
      "weighted avg       0.96      0.96      0.96        45\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# 方法1：直接使用模型的score方法计算正确率\n",
    "print(knn.score(X_test,y_test))\n",
    "\n",
    "# 方法2：使用sklearn.metrics下的classification_report方法\n",
    "# 先对测试集进行预测\n",
    "y_pred = knn.predict(X_test) #预测类别标签\n",
    "y_pred_prob = knn.predict_proba(X_test) #预测类别概率\n",
    "\n",
    "# 分类评估报告classification_report\n",
    "from sklearn.metrics import classification_report\n",
    "print(classification_report(y_test,y_pred))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0df6083b-cbbf-4a68-8324-453eae81616e",
   "metadata": {},
   "source": [
    "你提供的是一个分类模型的性能评估报告，通常称为混淆矩阵。这个报告展示了模型在三个不同类别（0、1、2）上的表现，包括精确度（precision）、召回率（recall）、F1分数（f1-score）和支持度（support）。\n",
    "\n",
    "下面是每个类别的详细解释：\n",
    "\n",
    "- **类别0**：\n",
    "  - 精确度（Precision）：1.00，意味着所有预测为类别0的样本都是正确的。\n",
    "  - 召回率（Recall）：1.00，意味着所有实际为类别0的样本都被正确预测。\n",
    "  - F1分数（F1-Score）：1.00，精确度和召回率的调和平均数，也是1.00，表示模型在类别0上的表现完美。\n",
    "  - 支持度（Support）：14，表示测试集中有14个样本属于类别0。\n",
    "\n",
    "- **类别1**：\n",
    "  - 精确度（Precision）：1.00，意味着所有预测为类别1的样本都是正确的。\n",
    "  - 召回率（Recall）：0.88，意味着有88%的实际类别1样本被正确预测。\n",
    "  - F1分数（F1-Score）：0.93，精确度和召回率的调和平均数，表示模型在类别1上的表现接近完美，但略低于类别0。\n",
    "  - 支持度（Support）：16，表示测试集中有16个样本属于类别1。\n",
    "\n",
    "- **类别2**：\n",
    "  - 精确度（Precision）：0.88，意味着有88%的预测为类别2的样本是正确的。\n",
    "  - 召回率（Recall）：1.00，意味着所有实际为类别2的样本都被正确预测。\n",
    "  - F1分数（F1-Score）：0.94，精确度和召回率的调和平均数，表示模型在类别2上的表现也接近完美。\n",
    "  - 支持度（Support）：15，表示测试集中有15个样本属于类别2。\n",
    "\n",
    "- **整体性能**：\n",
    "  - 准确度（Accuracy）：0.96，意味着模型在所有测试样本上的整体正确率为96%。\n",
    "  - 宏平均（Macro Avg）：精确度、召回率和F1分数的平均值都是0.96，表示模型在所有类别上的平均表现。\n",
    "  - 加权平均（Weighted Avg）：精确度、召回率和F1分数的加权平均值，考虑了每个类别的支持度。这里的加权平均值也是0.96，表示模型在所有类别上的整体表现。\n",
    "\n",
    "这个报告表明，模型在所有类别上的表现都非常好，整体准确度很高。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2359bae3-3ba7-48ea-a8e4-097f0b5e3f96",
   "metadata": {},
   "source": [
    "## 作业"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 131,
   "id": "95f4d49a-5a3e-40d7-9262-35f2a5114411",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "data = pd.read_csv(\"wine.txt\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 132,
   "id": "6c90ac62-c712-4bf7-a134-a8225fa2f993",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>1</th>\n",
       "      <th>14.23</th>\n",
       "      <th>1.71</th>\n",
       "      <th>2.43</th>\n",
       "      <th>15.6</th>\n",
       "      <th>127</th>\n",
       "      <th>2.8</th>\n",
       "      <th>3.06</th>\n",
       "      <th>.28</th>\n",
       "      <th>2.29</th>\n",
       "      <th>5.64</th>\n",
       "      <th>1.04</th>\n",
       "      <th>3.92</th>\n",
       "      <th>1065</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1</td>\n",
       "      <td>13.20</td>\n",
       "      <td>1.78</td>\n",
       "      <td>2.14</td>\n",
       "      <td>11.2</td>\n",
       "      <td>100</td>\n",
       "      <td>2.65</td>\n",
       "      <td>2.76</td>\n",
       "      <td>0.26</td>\n",
       "      <td>1.28</td>\n",
       "      <td>4.38</td>\n",
       "      <td>1.05</td>\n",
       "      <td>3.40</td>\n",
       "      <td>1050</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1</td>\n",
       "      <td>13.16</td>\n",
       "      <td>2.36</td>\n",
       "      <td>2.67</td>\n",
       "      <td>18.6</td>\n",
       "      <td>101</td>\n",
       "      <td>2.80</td>\n",
       "      <td>3.24</td>\n",
       "      <td>0.30</td>\n",
       "      <td>2.81</td>\n",
       "      <td>5.68</td>\n",
       "      <td>1.03</td>\n",
       "      <td>3.17</td>\n",
       "      <td>1185</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1</td>\n",
       "      <td>14.37</td>\n",
       "      <td>1.95</td>\n",
       "      <td>2.50</td>\n",
       "      <td>16.8</td>\n",
       "      <td>113</td>\n",
       "      <td>3.85</td>\n",
       "      <td>3.49</td>\n",
       "      <td>0.24</td>\n",
       "      <td>2.18</td>\n",
       "      <td>7.80</td>\n",
       "      <td>0.86</td>\n",
       "      <td>3.45</td>\n",
       "      <td>1480</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1</td>\n",
       "      <td>13.24</td>\n",
       "      <td>2.59</td>\n",
       "      <td>2.87</td>\n",
       "      <td>21.0</td>\n",
       "      <td>118</td>\n",
       "      <td>2.80</td>\n",
       "      <td>2.69</td>\n",
       "      <td>0.39</td>\n",
       "      <td>1.82</td>\n",
       "      <td>4.32</td>\n",
       "      <td>1.04</td>\n",
       "      <td>2.93</td>\n",
       "      <td>735</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1</td>\n",
       "      <td>14.20</td>\n",
       "      <td>1.76</td>\n",
       "      <td>2.45</td>\n",
       "      <td>15.2</td>\n",
       "      <td>112</td>\n",
       "      <td>3.27</td>\n",
       "      <td>3.39</td>\n",
       "      <td>0.34</td>\n",
       "      <td>1.97</td>\n",
       "      <td>6.75</td>\n",
       "      <td>1.05</td>\n",
       "      <td>2.85</td>\n",
       "      <td>1450</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>...</th>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "      <td>...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>172</th>\n",
       "      <td>3</td>\n",
       "      <td>13.71</td>\n",
       "      <td>5.65</td>\n",
       "      <td>2.45</td>\n",
       "      <td>20.5</td>\n",
       "      <td>95</td>\n",
       "      <td>1.68</td>\n",
       "      <td>0.61</td>\n",
       "      <td>0.52</td>\n",
       "      <td>1.06</td>\n",
       "      <td>7.70</td>\n",
       "      <td>0.64</td>\n",
       "      <td>1.74</td>\n",
       "      <td>740</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>173</th>\n",
       "      <td>3</td>\n",
       "      <td>13.40</td>\n",
       "      <td>3.91</td>\n",
       "      <td>2.48</td>\n",
       "      <td>23.0</td>\n",
       "      <td>102</td>\n",
       "      <td>1.80</td>\n",
       "      <td>0.75</td>\n",
       "      <td>0.43</td>\n",
       "      <td>1.41</td>\n",
       "      <td>7.30</td>\n",
       "      <td>0.70</td>\n",
       "      <td>1.56</td>\n",
       "      <td>750</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>174</th>\n",
       "      <td>3</td>\n",
       "      <td>13.27</td>\n",
       "      <td>4.28</td>\n",
       "      <td>2.26</td>\n",
       "      <td>20.0</td>\n",
       "      <td>120</td>\n",
       "      <td>1.59</td>\n",
       "      <td>0.69</td>\n",
       "      <td>0.43</td>\n",
       "      <td>1.35</td>\n",
       "      <td>10.20</td>\n",
       "      <td>0.59</td>\n",
       "      <td>1.56</td>\n",
       "      <td>835</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>175</th>\n",
       "      <td>3</td>\n",
       "      <td>13.17</td>\n",
       "      <td>2.59</td>\n",
       "      <td>2.37</td>\n",
       "      <td>20.0</td>\n",
       "      <td>120</td>\n",
       "      <td>1.65</td>\n",
       "      <td>0.68</td>\n",
       "      <td>0.53</td>\n",
       "      <td>1.46</td>\n",
       "      <td>9.30</td>\n",
       "      <td>0.60</td>\n",
       "      <td>1.62</td>\n",
       "      <td>840</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>176</th>\n",
       "      <td>3</td>\n",
       "      <td>14.13</td>\n",
       "      <td>4.10</td>\n",
       "      <td>2.74</td>\n",
       "      <td>24.5</td>\n",
       "      <td>96</td>\n",
       "      <td>2.05</td>\n",
       "      <td>0.76</td>\n",
       "      <td>0.56</td>\n",
       "      <td>1.35</td>\n",
       "      <td>9.20</td>\n",
       "      <td>0.61</td>\n",
       "      <td>1.60</td>\n",
       "      <td>560</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "<p>177 rows × 14 columns</p>\n",
       "</div>"
      ],
      "text/plain": [
       "     1  14.23  1.71  2.43  15.6  127   2.8  3.06   .28  2.29   5.64  1.04  \\\n",
       "0    1  13.20  1.78  2.14  11.2  100  2.65  2.76  0.26  1.28   4.38  1.05   \n",
       "1    1  13.16  2.36  2.67  18.6  101  2.80  3.24  0.30  2.81   5.68  1.03   \n",
       "2    1  14.37  1.95  2.50  16.8  113  3.85  3.49  0.24  2.18   7.80  0.86   \n",
       "3    1  13.24  2.59  2.87  21.0  118  2.80  2.69  0.39  1.82   4.32  1.04   \n",
       "4    1  14.20  1.76  2.45  15.2  112  3.27  3.39  0.34  1.97   6.75  1.05   \n",
       "..  ..    ...   ...   ...   ...  ...   ...   ...   ...   ...    ...   ...   \n",
       "172  3  13.71  5.65  2.45  20.5   95  1.68  0.61  0.52  1.06   7.70  0.64   \n",
       "173  3  13.40  3.91  2.48  23.0  102  1.80  0.75  0.43  1.41   7.30  0.70   \n",
       "174  3  13.27  4.28  2.26  20.0  120  1.59  0.69  0.43  1.35  10.20  0.59   \n",
       "175  3  13.17  2.59  2.37  20.0  120  1.65  0.68  0.53  1.46   9.30  0.60   \n",
       "176  3  14.13  4.10  2.74  24.5   96  2.05  0.76  0.56  1.35   9.20  0.61   \n",
       "\n",
       "     3.92  1065  \n",
       "0    3.40  1050  \n",
       "1    3.17  1185  \n",
       "2    3.45  1480  \n",
       "3    2.93   735  \n",
       "4    2.85  1450  \n",
       "..    ...   ...  \n",
       "172  1.74   740  \n",
       "173  1.56   750  \n",
       "174  1.56   835  \n",
       "175  1.62   840  \n",
       "176  1.60   560  \n",
       "\n",
       "[177 rows x 14 columns]"
      ]
     },
     "execution_count": 132,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 133,
   "id": "ee052406-2770-4bda-bfca-f0924e87e7f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "a=data.columns\n",
    "b=list(a)\n",
    "c=np.zeros(14,dtype=float)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 134,
   "id": "4c18a850-f08a-4592-ab0a-9fcf10b43b70",
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(len(b)):\n",
    "    c[i]=float(b[i])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 135,
   "id": "d4083be9-91dc-41e1-b49e-0549dbb62891",
   "metadata": {},
   "outputs": [],
   "source": [
    "data.loc[177]=c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 136,
   "id": "c1e7a9f1-dccc-4676-92be-e7a6c866042f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,\n",
       "       1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,\n",
       "       1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,\n",
       "       1., 1., 1., 1., 1., 1., 1., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,\n",
       "       2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,\n",
       "       2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,\n",
       "       2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 2.,\n",
       "       2., 2., 2., 2., 2., 2., 2., 2., 2., 2., 3., 3., 3., 3., 3., 3., 3.,\n",
       "       3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3.,\n",
       "       3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3., 3.,\n",
       "       3., 3., 3., 3., 3., 3., 3., 1.])"
      ]
     },
     "execution_count": 136,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y=data[\"1\"]\n",
    "y=np.array(y)\n",
    "y"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 137,
   "id": "e2e6e227-d18c-4889-99f9-273a8ab91cc4",
   "metadata": {},
   "outputs": [],
   "source": [
    "x0=np.array(data.loc[0:178])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 138,
   "id": "b9e0972c-eef5-4a30-9292-3f276b797bc0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1.320e+01, 1.780e+00, 2.140e+00, ..., 1.050e+00, 3.400e+00,\n",
       "        1.050e+03],\n",
       "       [1.316e+01, 2.360e+00, 2.670e+00, ..., 1.030e+00, 3.170e+00,\n",
       "        1.185e+03],\n",
       "       [1.437e+01, 1.950e+00, 2.500e+00, ..., 8.600e-01, 3.450e+00,\n",
       "        1.480e+03],\n",
       "       ...,\n",
       "       [1.317e+01, 2.590e+00, 2.370e+00, ..., 6.000e-01, 1.620e+00,\n",
       "        8.400e+02],\n",
       "       [1.413e+01, 4.100e+00, 2.740e+00, ..., 6.100e-01, 1.600e+00,\n",
       "        5.600e+02],\n",
       "       [1.423e+01, 1.710e+00, 2.430e+00, ..., 1.040e+00, 3.920e+00,\n",
       "        1.065e+03]])"
      ]
     },
     "execution_count": 138,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = np.delete(x0, 0, axis=1)\n",
    "x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 139,
   "id": "dfc4c68e-7023-4eba-a999-8cc939aa8573",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.8148148148148148\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "         1.0       1.00      1.00      1.00        18\n",
      "         2.0       0.79      0.79      0.79        24\n",
      "         3.0       0.58      0.58      0.58        12\n",
      "\n",
      "    accuracy                           0.81        54\n",
      "   macro avg       0.79      0.79      0.79        54\n",
      "weighted avg       0.81      0.81      0.81        54\n",
      "\n"
     ]
    }
   ],
   "source": [
    "X_train,X_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=1024)  \n",
    "knn.fit(X_train,y_train)\n",
    "\n",
    "# 方法1：直接使用模型的score方法计算正确率\n",
    "print(knn.score(X_test,y_test))\n",
    "\n",
    "# 方法2：使用sklearn.metrics下的classification_report方法\n",
    "# 先对测试集进行预测\n",
    "y_pred = knn.predict(X_test) #预测类别标签\n",
    "y_pred_prob = knn.predict_proba(X_test) #预测类别概率\n",
    "\n",
    "# 分类评估报告classification_report\n",
    "from sklearn.metrics import classification_report\n",
    "print(classification_report(y_test,y_pred))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7d83366-bbdc-490b-89c5-9c1d205ad676",
   "metadata": {},
   "source": [
    "# 作业"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83de3dcd-4d7e-4fcd-8097-073dbff24b48",
   "metadata": {},
   "source": [
    "###  k近邻法的三要素"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8416e0d6-f69b-4ced-a235-1e66dbcfee2e",
   "metadata": {},
   "source": [
    "- 距离度量（Distance Metric）：k近邻法中，首先需要确定一个距离度量标准来计算不同数据点之间的相似度。常用的距离度量包括欧氏距离、曼哈顿距离、闵可夫斯基距离等。\n",
    "\n",
    "- k值的选择（Choice of k）：k值即最近邻居的数目，是k近邻算法中的一个重要参数。k值的选择会对分类结果产生显著影响。较小的k值意味着模型会更多地受到噪声和异常值的影响，而较大的k值则可能导致模型过于平滑，无法捕捉数据的局部特征。\n",
    "\n",
    "- 分类决策规则（Classification Decision Rule）：在确定了k个最近邻之后，需要一个规则来决定新数据点的分类。最常见的决策规则是多数投票法，即选取k个最近邻中出现次数最多的类别作为预测类别。\n",
    "  "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f95e12b-64e4-4ac3-8837-a5de03bb7b6a",
   "metadata": {},
   "source": [
    "### k近邻法的特点"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b043ab36-ea64-49ca-bf4d-8c66c18955a0",
   "metadata": {},
   "source": [
    "- 基于实例的学习：直接利用训练数据进行预测，不需要学习一个判别函数。\n",
    "- 非参数方法：不假设数据分布，适用于非线性问题。\n",
    "- 多数投票决策：通过k个最近邻的多数类别来决定新样本的分类。\n",
    "- 对噪声敏感：对训练数据中的噪声和异常值较为敏感。\n",
    "- 计算复杂度：预测时需要计算新样本与所有训练样本的距离，计算量大。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "082c5199-3124-4879-ae72-f153b9f00a95",
   "metadata": {},
   "source": [
    "### 题目：已知标签labels=[\"A\",\"B\",\"C\",\"D\"],对应数据组为([[1.0,1.1],[2.0,2.0],[0,0],[4.1,5.1]]),利用k近邻法对其进行近邻分类。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4f8c9d5b-32e9-43e0-bc35-0b931435f6b1",
   "metadata": {},
   "source": [
    "#### 一"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3b39ed11-262b-41af-957c-eac239f7fdd0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "\n",
    "labels=np.array([\"A\",\"B\",\"C\",\"D\"])\n",
    "data=np.array([[1.0,1.1],[2.0,2.0],[0,0],[4.1,5.1]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "id": "2d5a7b04-e978-46e1-8a37-d62e8d5f3568",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "\n",
    "knn=KNeighborsClassifier(n_neighbors=1, weights=\"uniform\", algorithm=\"auto\", leaf_size=30, p=2, \n",
    "                         metric=\"minkowski\", metric_params=None, n_jobs=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "id": "07161e27-8e90-40fc-8bed-618c23810bbe",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<style>#sk-container-id-7 {\n",
       "  /* Definition of color scheme common for light and dark mode */\n",
       "  --sklearn-color-text: black;\n",
       "  --sklearn-color-line: gray;\n",
       "  /* Definition of color scheme for unfitted estimators */\n",
       "  --sklearn-color-unfitted-level-0: #fff5e6;\n",
       "  --sklearn-color-unfitted-level-1: #f6e4d2;\n",
       "  --sklearn-color-unfitted-level-2: #ffe0b3;\n",
       "  --sklearn-color-unfitted-level-3: chocolate;\n",
       "  /* Definition of color scheme for fitted estimators */\n",
       "  --sklearn-color-fitted-level-0: #f0f8ff;\n",
       "  --sklearn-color-fitted-level-1: #d4ebff;\n",
       "  --sklearn-color-fitted-level-2: #b3dbfd;\n",
       "  --sklearn-color-fitted-level-3: cornflowerblue;\n",
       "\n",
       "  /* Specific color for light theme */\n",
       "  --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, white)));\n",
       "  --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, black)));\n",
       "  --sklearn-color-icon: #696969;\n",
       "\n",
       "  @media (prefers-color-scheme: dark) {\n",
       "    /* Redefinition of color scheme for dark theme */\n",
       "    --sklearn-color-text-on-default-background: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-background: var(--sg-background-color, var(--theme-background, var(--jp-layout-color0, #111)));\n",
       "    --sklearn-color-border-box: var(--sg-text-color, var(--theme-code-foreground, var(--jp-content-font-color1, white)));\n",
       "    --sklearn-color-icon: #878787;\n",
       "  }\n",
       "}\n",
       "\n",
       "#sk-container-id-7 {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 pre {\n",
       "  padding: 0;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 input.sk-hidden--visually {\n",
       "  border: 0;\n",
       "  clip: rect(1px 1px 1px 1px);\n",
       "  clip: rect(1px, 1px, 1px, 1px);\n",
       "  height: 1px;\n",
       "  margin: -1px;\n",
       "  overflow: hidden;\n",
       "  padding: 0;\n",
       "  position: absolute;\n",
       "  width: 1px;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-dashed-wrapped {\n",
       "  border: 1px dashed var(--sklearn-color-line);\n",
       "  margin: 0 0.4em 0.5em 0.4em;\n",
       "  box-sizing: border-box;\n",
       "  padding-bottom: 0.4em;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-container {\n",
       "  /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n",
       "     but bootstrap.min.css set `[hidden] { display: none !important; }`\n",
       "     so we also need the `!important` here to be able to override the\n",
       "     default hidden behavior on the sphinx rendered scikit-learn.org.\n",
       "     See: https://github.com/scikit-learn/scikit-learn/issues/21755 */\n",
       "  display: inline-block !important;\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-text-repr-fallback {\n",
       "  display: none;\n",
       "}\n",
       "\n",
       "div.sk-parallel-item,\n",
       "div.sk-serial,\n",
       "div.sk-item {\n",
       "  /* draw centered vertical line to link estimators */\n",
       "  background-image: linear-gradient(var(--sklearn-color-text-on-default-background), var(--sklearn-color-text-on-default-background));\n",
       "  background-size: 2px 100%;\n",
       "  background-repeat: no-repeat;\n",
       "  background-position: center center;\n",
       "}\n",
       "\n",
       "/* Parallel-specific style estimator block */\n",
       "\n",
       "#sk-container-id-7 div.sk-parallel-item::after {\n",
       "  content: \"\";\n",
       "  width: 100%;\n",
       "  border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n",
       "  flex-grow: 1;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-parallel {\n",
       "  display: flex;\n",
       "  align-items: stretch;\n",
       "  justify-content: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  position: relative;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-parallel-item {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-parallel-item:first-child::after {\n",
       "  align-self: flex-end;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-parallel-item:last-child::after {\n",
       "  align-self: flex-start;\n",
       "  width: 50%;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-parallel-item:only-child::after {\n",
       "  width: 0;\n",
       "}\n",
       "\n",
       "/* Serial-specific style estimator block */\n",
       "\n",
       "#sk-container-id-7 div.sk-serial {\n",
       "  display: flex;\n",
       "  flex-direction: column;\n",
       "  align-items: center;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  padding-right: 1em;\n",
       "  padding-left: 1em;\n",
       "}\n",
       "\n",
       "\n",
       "/* Toggleable style: style used for estimator/Pipeline/ColumnTransformer box that is\n",
       "clickable and can be expanded/collapsed.\n",
       "- Pipeline and ColumnTransformer use this feature and define the default style\n",
       "- Estimators will overwrite some part of the style using the `sk-estimator` class\n",
       "*/\n",
       "\n",
       "/* Pipeline and ColumnTransformer style (default) */\n",
       "\n",
       "#sk-container-id-7 div.sk-toggleable {\n",
       "  /* Default theme specific background. It is overwritten whether we have a\n",
       "  specific estimator or a Pipeline/ColumnTransformer */\n",
       "  background-color: var(--sklearn-color-background);\n",
       "}\n",
       "\n",
       "/* Toggleable label */\n",
       "#sk-container-id-7 label.sk-toggleable__label {\n",
       "  cursor: pointer;\n",
       "  display: block;\n",
       "  width: 100%;\n",
       "  margin-bottom: 0;\n",
       "  padding: 0.5em;\n",
       "  box-sizing: border-box;\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 label.sk-toggleable__label-arrow:before {\n",
       "  /* Arrow on the left of the label */\n",
       "  content: \"▸\";\n",
       "  float: left;\n",
       "  margin-right: 0.25em;\n",
       "  color: var(--sklearn-color-icon);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 label.sk-toggleable__label-arrow:hover:before {\n",
       "  color: var(--sklearn-color-text);\n",
       "}\n",
       "\n",
       "/* Toggleable content - dropdown */\n",
       "\n",
       "#sk-container-id-7 div.sk-toggleable__content {\n",
       "  max-height: 0;\n",
       "  max-width: 0;\n",
       "  overflow: hidden;\n",
       "  text-align: left;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-toggleable__content.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-toggleable__content pre {\n",
       "  margin: 0.2em;\n",
       "  border-radius: 0.25em;\n",
       "  color: var(--sklearn-color-text);\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-toggleable__content.fitted pre {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 input.sk-toggleable__control:checked~div.sk-toggleable__content {\n",
       "  /* Expand drop-down */\n",
       "  max-height: 200px;\n",
       "  max-width: 100%;\n",
       "  overflow: auto;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {\n",
       "  content: \"▾\";\n",
       "}\n",
       "\n",
       "/* Pipeline/ColumnTransformer-specific style */\n",
       "\n",
       "#sk-container-id-7 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator-specific style */\n",
       "\n",
       "/* Colorize estimator box */\n",
       "#sk-container-id-7 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-label label.sk-toggleable__label,\n",
       "#sk-container-id-7 div.sk-label label {\n",
       "  /* The background is the default theme color */\n",
       "  color: var(--sklearn-color-text-on-default-background);\n",
       "}\n",
       "\n",
       "/* On hover, darken the color of the background */\n",
       "#sk-container-id-7 div.sk-label:hover label.sk-toggleable__label {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "/* Label box, darken color on hover, fitted */\n",
       "#sk-container-id-7 div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n",
       "  color: var(--sklearn-color-text);\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Estimator label */\n",
       "\n",
       "#sk-container-id-7 div.sk-label label {\n",
       "  font-family: monospace;\n",
       "  font-weight: bold;\n",
       "  display: inline-block;\n",
       "  line-height: 1.2em;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-label-container {\n",
       "  text-align: center;\n",
       "}\n",
       "\n",
       "/* Estimator-specific */\n",
       "#sk-container-id-7 div.sk-estimator {\n",
       "  font-family: monospace;\n",
       "  border: 1px dotted var(--sklearn-color-border-box);\n",
       "  border-radius: 0.25em;\n",
       "  box-sizing: border-box;\n",
       "  margin-bottom: 0.5em;\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-0);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-estimator.fitted {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-0);\n",
       "}\n",
       "\n",
       "/* on hover */\n",
       "#sk-container-id-7 div.sk-estimator:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-2);\n",
       "}\n",
       "\n",
       "#sk-container-id-7 div.sk-estimator.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-2);\n",
       "}\n",
       "\n",
       "/* Specification for estimator info (e.g. \"i\" and \"?\") */\n",
       "\n",
       "/* Common style for \"i\" and \"?\" */\n",
       "\n",
       ".sk-estimator-doc-link,\n",
       "a:link.sk-estimator-doc-link,\n",
       "a:visited.sk-estimator-doc-link {\n",
       "  float: right;\n",
       "  font-size: smaller;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1em;\n",
       "  height: 1em;\n",
       "  width: 1em;\n",
       "  text-decoration: none !important;\n",
       "  margin-left: 1ex;\n",
       "  /* unfitted */\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted,\n",
       "a:link.sk-estimator-doc-link.fitted,\n",
       "a:visited.sk-estimator-doc-link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "div.sk-estimator:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link:hover,\n",
       ".sk-estimator-doc-link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "div.sk-estimator.fitted:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover,\n",
       "div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n",
       ".sk-estimator-doc-link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "/* Span, style for the box shown on hovering the info icon */\n",
       ".sk-estimator-doc-link span {\n",
       "  display: none;\n",
       "  z-index: 9999;\n",
       "  position: relative;\n",
       "  font-weight: normal;\n",
       "  right: .2ex;\n",
       "  padding: .5ex;\n",
       "  margin: .5ex;\n",
       "  width: min-content;\n",
       "  min-width: 20ex;\n",
       "  max-width: 50ex;\n",
       "  color: var(--sklearn-color-text);\n",
       "  box-shadow: 2pt 2pt 4pt #999;\n",
       "  /* unfitted */\n",
       "  background: var(--sklearn-color-unfitted-level-0);\n",
       "  border: .5pt solid var(--sklearn-color-unfitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link.fitted span {\n",
       "  /* fitted */\n",
       "  background: var(--sklearn-color-fitted-level-0);\n",
       "  border: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "\n",
       ".sk-estimator-doc-link:hover span {\n",
       "  display: block;\n",
       "}\n",
       "\n",
       "/* \"?\"-specific style due to the `<a>` HTML tag */\n",
       "\n",
       "#sk-container-id-7 a.estimator_doc_link {\n",
       "  float: right;\n",
       "  font-size: 1rem;\n",
       "  line-height: 1em;\n",
       "  font-family: monospace;\n",
       "  background-color: var(--sklearn-color-background);\n",
       "  border-radius: 1rem;\n",
       "  height: 1rem;\n",
       "  width: 1rem;\n",
       "  text-decoration: none;\n",
       "  /* unfitted */\n",
       "  color: var(--sklearn-color-unfitted-level-1);\n",
       "  border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 a.estimator_doc_link.fitted {\n",
       "  /* fitted */\n",
       "  border: var(--sklearn-color-fitted-level-1) 1pt solid;\n",
       "  color: var(--sklearn-color-fitted-level-1);\n",
       "}\n",
       "\n",
       "/* On hover */\n",
       "#sk-container-id-7 a.estimator_doc_link:hover {\n",
       "  /* unfitted */\n",
       "  background-color: var(--sklearn-color-unfitted-level-3);\n",
       "  color: var(--sklearn-color-background);\n",
       "  text-decoration: none;\n",
       "}\n",
       "\n",
       "#sk-container-id-7 a.estimator_doc_link.fitted:hover {\n",
       "  /* fitted */\n",
       "  background-color: var(--sklearn-color-fitted-level-3);\n",
       "}\n",
       "</style><div id=\"sk-container-id-7\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>KNeighborsClassifier(n_jobs=1, n_neighbors=1)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator fitted sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-7\" type=\"checkbox\" checked><label for=\"sk-estimator-id-7\" class=\"sk-toggleable__label fitted sk-toggleable__label-arrow fitted\">&nbsp;&nbsp;KNeighborsClassifier<a class=\"sk-estimator-doc-link fitted\" rel=\"noreferrer\" target=\"_blank\" href=\"https://scikit-learn.org/1.4/modules/generated/sklearn.neighbors.KNeighborsClassifier.html\">?<span>Documentation for KNeighborsClassifier</span></a><span class=\"sk-estimator-doc-link fitted\">i<span>Fitted</span></span></label><div class=\"sk-toggleable__content fitted\"><pre>KNeighborsClassifier(n_jobs=1, n_neighbors=1)</pre></div> </div></div></div></div>"
      ],
      "text/plain": [
       "KNeighborsClassifier(n_jobs=1, n_neighbors=1)"
      ]
     },
     "execution_count": 102,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "knn.fit(data,labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 111,
   "id": "da632b7d-9652-4a59-9553-5d83f7123449",
   "metadata": {},
   "outputs": [],
   "source": [
    "data_test=np.array([[2.3,2.1],[5.3,5.9]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 112,
   "id": "4c9b2d88-7337-45e4-9b06-00f53bab7fe6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array(['B', 'D'], dtype='<U1')"
      ]
     },
     "execution_count": 112,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_pred = knn.predict(data_test) #预测类别标签\n",
    "y_pred_prob = knn.predict_proba(data_test) #预测类别概率\n",
    "y_pred"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cafe1360-a2c7-4b3e-b847-2302951ffd44",
   "metadata": {},
   "source": [
    "####  二"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 117,
   "id": "b8cbb9fd-ef61-44ac-b26a-ee007720f16b",
   "metadata": {},
   "outputs": [],
   "source": [
    "data_test=np.array([[2.3,2.1],[5.3,5.9]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 123,
   "id": "a22703f0-17cb-4169-81ab-ceb478e2353b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "data_pred is B\n",
      "data_pred is D\n"
     ]
    }
   ],
   "source": [
    "def knn(test):\n",
    "    import numpy as np\n",
    "    labels=np.array([\"A\",\"B\",\"C\",\"D\"])\n",
    "    data=np.array([[1.0,1.1],[2.0,2.0],[0,0],[4.1,5.1]])\n",
    "    a=len(test)\n",
    "    b=len(data)\n",
    "    distance=np.zeros((a,b),dtype=float)\n",
    "    for i in range(a):\n",
    "        for j in range(b):                                                                           ##n_neighbors=4\n",
    "            dt=((test[i][0]-data[j][0])**2+(test[i][1]-data[j][1])**2)**0.5 \n",
    "            distance[i][j]=dt\n",
    "    for i in range(a):\n",
    "        min_dt=min(distance[i])\n",
    "        for j in range(b):\n",
    "            if distance[i][j]==min_dt:\n",
    "                print(\"data_pred is\",labels[j])\n",
    "            \n",
    "            \n",
    "knn(data_test)                "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ae748376-4c17-421f-911b-53ab9eea2306",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
